package com.guigu.pd.dispatch.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigu.pd.dispatch.entity.ScheduleJobEntity;
import com.guigu.pd.dispatch.jobs.ScheduleJob;
import com.guigu.pd.dispatch.service.ScheduleJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/dispatch/quartz")
public class QuartzController {
    //注入调度器对象
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ScheduleJobService scheduleJobService;


    /**
     * 添加定时任务
     *
     * @param bizId 标识的要触发哪个定时任务（机构编号）
     * @param cronExpression  定时任务触发的时间
     * @return
     */
    @GetMapping("/savequartz/{bizId}/{cronExpression}")
    public String savequartz(@PathVariable("bizId") String bizId,@PathVariable("cronExpression") String cronExpression) throws Exception {

        //TODO 添加schedule_job表数据


        //构建job信息 创建任务示例对象
        JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(bizId).build();

        jobDetail.getJobDataMap().put("bizId", bizId);

   String str = cronExpression + " ?";

        //表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(str)
                //表示错过了时间表示下一次触发时间
                .withMisfireHandlingInstructionDoNothing();

        //按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(bizId).withSchedule(scheduleBuilder).build();

        //关联任务和触发器
        scheduler.scheduleJob(jobDetail, trigger);
        return "OK";
    }

    /**
     * 暂停定时任务
     * @param bizId
     * @return
     */
    @GetMapping("/pausequartz/{bizId}")
    public String pause(@PathVariable("bizId") String bizId) throws Exception{
        JobKey jobKey = JobKey.jobKey(bizId);
        scheduler.pauseJob(jobKey);

        //修改状态
        LambdaQueryWrapper<ScheduleJobEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ScheduleJobEntity::getBusinessId,bizId);
        scheduleJobService.remove(lambdaQueryWrapper);

        return "OK";
    }

    /**
     * 恢复定时任务
     * @param bizId
     * @return
     */
    @PutMapping("/resumequartz/{bizId}")
    public String resume(@PathVariable("bizId") String bizId) throws Exception{
        JobKey jobKey = JobKey.jobKey(bizId);
        scheduler.resumeJob(jobKey);
        return "OK";
    }

    /**
     * 删除定时任务
     * @param bizId
     * @return
     */
    @DeleteMapping("/deletequartz/{bizId}")
    public String deletequartz(@PathVariable("bizId") String bizId) throws Exception{
        JobKey jobKey = JobKey.jobKey(bizId);
        scheduler.deleteJob(jobKey);

        return "OK";
    }

    /**
     * 立即执行定时任务
     * @param bizId
     * @return
     */
    @PutMapping("/runquartz/{bizId}")
    public String run(@PathVariable("bizId") String bizId) throws Exception{

        JobKey jobKey = JobKey.jobKey("TASK_"+bizId);
        scheduler.triggerJob(jobKey);
        return "OK";
    }

    /**
     * 更新定时任务
     * @param bizId
     * @param cronExpression
     * @return
     * @throws Exception
     */
    @GetMapping("/updatequartz/{bizId}/{cronExpression}")
    public String update(@PathVariable("bizId") String bizId,@PathVariable("cronExpression") String cronExpression) throws Exception{

        TriggerKey triggerKey = TriggerKey.triggerKey(bizId);

        String str = cronExpression + " ?";

        //表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(str)
                .withMisfireHandlingInstructionDoNothing();

        //获取触发器对象
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

        //按新的cronExpression表达式重新构建trigger
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

        scheduler.rescheduleJob(triggerKey, trigger);
        return "OK";
    }

}
